<template>
  <div class="container">
      <div class="logo">
      <img src="http://static.catone-vip.com/20190228/5c778d3534feb"/>
    </div>
    <van-cell-group :border="false">
      <van-field :value="form.phone" data-name="phone" clearable placeholder="请输入手机号" @change="onChangeField"/>
      <van-field :value="form.code" clearable center data-name="code" placeholder="请输入短信验证码" @change="onChangeField" use-button-slot>
        <van-button class="mk-button" slot="button" size="small" type="default" :disabled="send_code_btn_disabled" @click="sendCode">{{send_code_btn_text}}</van-button>
      </van-field>
      <van-field :value="form.passwords" data-name="passwords" type="password" clearable placeholder="请输入密码" @change="onChangeField"/>
    </van-cell-group>
    <div class="btn">
      <van-button class="mk-button" type="primary" size="normal" block :loading="bindLoading" @click="bindPhone">立即绑定</van-button>
    </div>
    <van-toast id="van-toast" />
  </div>
</template>

<script>
import * as CommonAction from '@/api/common'
import * as AuthAction from '@/api/auth'
import Toast from 'vant-weapp/dist/toast/toast'
import Utils from '@/utils'
import {mapState} from 'vuex'

export default {
  data () {
    return {
      form: {
        phone: '',
        code: '',
        passwords: ''
      },
      bindLoading: false,
      send_code_btn_text: '发送验证码',
      send_code_btn_disabled: false,
      timer: 0
    }
  },
  computed: {
    ...mapState(['me'])
  },
  methods: {
    onChangeField (event) {
      this.form[event.currentTarget.dataset.name] = event.mp.detail
    },
    bindPhone () {
      if (!this.form.phone) {
        Toast('手机号不能为空')
        return
      }
      if (!Utils.validator.isMobile(this.form.phone)) {
        Toast('请输入有效的手机号')
        return
      }
      if (!this.form.passwords) {
        Toast('密码不能为空')
        return
      }
      if (!this.form.code) {
        Toast('验证码不能为空')
        return
      }
      if (wx.getStorageSync('__inviteCode')) {
        this.form.invite_code = wx.getStorageSync('__inviteCode')
      }
      if (this.bindLoading) return
      this.bindLoading = true
      this.form.mp_openid = wx.getStorageSync('openid')
      AuthAction.register(this.form).then(data => {
        this.$store.commit('set_me', data.me)
        wx.setStorageSync('token', data.token)
        this.handleTarget()
        this.bindLoading = false
      }).catch((err) => {
        Toast(err.msg)
        this.bindLoading = false
      })
    },
    sendCode () {
      if (this.timer > 0) return
      if (!this.form.phone) {
        Toast('手机号不能为空')
        return
      }
      if (!Utils.validator.isMobile(this.form.phone)) {
        Toast('请输入有效的手机号')
        return
      }
      this.timer = 60
      this.send_code_btn_text = this.timer + 's'
      this.send_code_btn_disabled = true
      var that = this
      var t = setInterval(function () {
        that.timer = that.timer - 1
        if (that.timer === 0) {
          clearInterval(t)
          that.send_code_btn_disabled = false
          that.send_code_btn_text = '发送验证码'
        } else {
          that.send_code_btn_text = that.timer + 's'
        }
      }, 1000)
      CommonAction.sendVerifyCode({ phone: this.form.phone })
        .then(() => { Toast('验证码已发送，请注意查看~') })
        .catch(err => Toast(err.msg))
    },
    handleTarget () {
      if (this.$root.$mp.query.target) {
        switch (this.$root.$mp.query.target) {
          case 'cart':
            wx.switchTab({
              url: '../cart/index'
            })
            break
          case 'goods':
            wx.redirectTo({
              url: '../product/detail?id=' + this.$root.$mp.query.id
            })
            break
          case 'posts':
            wx.redirectTo({
              url: '/pages/shop/index'
            })
            break
          case 'zy':
            wx.switchTab({ url: '../home/zy' })
            break
          case 'post-detail':
            wx.redirectTo({
              url: '/pages/post/detail?id=' + this.$root.$mp.query.id
            })
            break
        }
      } else {
        wx.switchTab({
          url: '../user/index'
        })
      }
    },
    fetchUserInfo () {
      let that = this
      wx.getUserInfo({
        lang: 'zh_CN',
        success: function (res) {
          that.form.sex = res.userInfo.gender
          that.form.nickname = res.userInfo.nickName
          that.form.avatar = res.userInfo.avatarUrl
        },
        fail (res) {
          Toast(res)
        }
      })
    }
  },
  beforeMount () {
    this.fetchUserInfo()
  }
}
</script>

<style lang="less" scoped>
.container {
  .btn {
    margin:55rpx 30rpx 30rpx;
  }
  .logo {
    display:flex;
    margin:70rpx 0 150rpx;
    img {
       width:140rpx;
      height:140rpx;
      margin: 0 auto;
    }
  }
}

</style>
